let house_id = 0
let house_index = 0
Page({
  data: {
    dialogVisible: false,
    isEmpty: false
  },
  onShow () {
    this.getHouseList()
  },
  // 房屋列表接口数据
  async getHouseList () {
    // 请求接口
    const { code, data: houseList } = await wx.http.get('/room')
    // 检测调用接口是否成功
    if (code !== 10000) return wx.utils.toast()
    // 解决个小bug  返回数据如果不为空就把isEmpty置成false

    // 渲染数据
    this.setData({
      houseList,
      isEmpty: houseList.length === 0
    })
    console.log(houseList)
  },
  swipeClose (ev) {
    const { position, instance } = ev.detail
    // console.log('ev', ev)
    // 取一下想要删除的房屋id和索引
    house_id = ev.mark.id
    house_index = ev.mark.index
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // swiper-cell 滑块关闭
      instance.close()
    }
  },
  // 当dialog弹窗关闭时触发
  closeDialog (e) {
    console.log('关闭弹窗', e)
    // 只有选择了确认,才调接口删除房屋
    // if (e.detail === 'confirm') {
    //   this.deleteHouse()
    // }
    e.detail === 'confirm' && this.deleteHouse()
  },
  // 删除房屋方法
  async deleteHouse () {
    console.log('我们真的要删除了')
    // 调用接口删除房屋
    const { code } = await wx.http.delete('/room/' + house_id)
    // 检测接口是否成功
    if (code !== 10000) return wx.utils.toast('删除房屋失败!')

    // 接口调用成功了
    this.data.houseList.splice(house_index, 1)
    this.setData({
      houseList: this.data.houseList,
      isEmpty: this.data.houseList.length === 0
    })
  },
  // 跳转详情页
  goDetail (e) {
    // 跳转到详情页需要携带id
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + e.mark.id,
    })
  },

  addHouse () {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },
})
